package com.zhiwei.codesecurity.web.common.utils;


import org.apache.log4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

import com.zhiwei.codesecurity.common.utils.IdMaker;

public class LoggerMDCFilter extends OncePerRequestFilter implements Filter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        try {
            // 为每一个请求创建一个ID，方便查找日志时可以根据ID查找出一个http请求所有相关日志
            MDC.put("req.id", IdMaker.generate());
            filterChain.doFilter(request, response);
        } finally {
            clearMDC();
        }
    }

    @SuppressWarnings("rawtypes")
    private void clearMDC() {
        Map map = MDC.getContext();
        if (map != null) {
            map.clear();
        }
    }
}
